import { ComponentInfoType, ComponentsStateType } from ".";

export const getNextSelectedId = (
  fe_id: string,
  componentList: ComponentInfoType[]
) => {
  const visibleComponentList = componentList.filter((c) => !c.isHidden);
  const index = visibleComponentList.findIndex((c) => c.fe_id === fe_id);
  if (index < 0) return "";

  let nextSelectedId = "";
  if (visibleComponentList[index + 1]) {
    nextSelectedId = visibleComponentList[index + 1].fe_id;
  } else if (visibleComponentList[index - 1]) {
    nextSelectedId = visibleComponentList[index - 1].fe_id;
  }

  return nextSelectedId;
};

/**
 * 插入新组件
 * @param draft
 * @param newComponent
 */
export const insertNewComponent = (
  draft: ComponentsStateType,
  newComponent: ComponentInfoType
) => {
  const { selectedId, componentList } = draft;
  const index = componentList.findIndex((c) => c.fe_id === selectedId);

  if (index === -1) {
    draft.componentList.push(newComponent);
  } else {
    draft.componentList.splice(index + 1, 0, newComponent);
  }

  draft.selectedId = newComponent.fe_id;
};
